import base from '../common/base.js'
import store from '../store/index.js'  

export default class Request {
    http(param) {
        // 请求参数
        var url = param.url,
            method = !param.method ? "GET" : param.method,
			data = param.data || {},
			hideLoading = param.hideLoading || true,
            header = {},
            token = store.state.token || "";
        //拼接完整请求地址 base.apiurl +
		var requestUrl = base.apiurl + url;
        //var requestUrl =  url;
		
        //请求方式:GET或POST(POST需配置
        // header: {'content-type' : "application/x-www-form-urlencoded"},)
        if (method) {
            method = method.toUpperCase(); //小写改为大写
			//统一都是json格式
			header = {
			    // 'content-type': "application/json",
				'authorization' :  token
			};
        }

        //加载圈
        if (!hideLoading) {
            uni.showLoading({
                title: '加载中...'
            });
        }

        // 返回promise
        return new Promise((resolve, reject) => {
            // 请求
            uni.request({
                url: requestUrl,
                data: data,
                method: method,
                header: header,
                success: (res) => {
					//console.log("res000=",res);
                    // 判断 请求api 格式是否正确
                    if (res.statusCode && res.statusCode != 200) {
                        uni.showToast({
                            title: "api错误,code:[" + res.statusCode+"]",
                            icon: 'error',
							duration:10000
                        });
                        return "error";
                    }
                    // 将结果抛出
                    resolve(res.data)
                },
                //请求失败
                fail: (e) => {
                    uni.showToast({
                        title: "" + e.errMsg,
                        icon: 'error',
						duration:10000
                    });
                    return(e.errMsg);
                },
                //请求完成
                complete() {
                    //隐藏加载
                    if (!hideLoading) {
                        uni.hideLoading();
                    }
                    resolve();
                    return;
                }
            })
        })
    }
}